package com.cevent.community.app.template.utils;/**
 * Created by Cevent on 2021/9/15.
 */

import com.cevent.community.app.template.generator.EnumsApplication;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map;

/**
 * @author cevent
 * @description freemarker代码自动化构建工具类
 * @date 2021/9/15 17:39
 */
public class FreemarkerUtil {
    private static final Logger LOG= LoggerFactory.getLogger(FreemarkerUtil.class);
    static String PARENT_DIR="com_cevent_communit_app";
    static String MAIN="varied_code_template";
    //1.定义模板路径，所有模板放在ftl
    static String ftlPath=PARENT_DIR+"\\"+MAIN+"\\src\\main\\java\\com\\cevent\\community\\app\\template\\ftl";
    //freemarker属性
    static Template template;
    //2.读取模板：初始化版本，根据pom（外部传入参数ftl-freemarker模板名称）
    public static void initConfig(String ftlName) throws IOException {
        //Configuration在freemarker-》2.3.31被deprecated声明不赞成，这里适用，引用版本号恢复正常
        Configuration configuration=new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDirectoryForTemplateLoading(new File(ftlPath));
        configuration.setObjectWrapper(new DefaultObjectWrapper(Configuration.VERSION_2_3_31));
        template=configuration.getTemplate(ftlName);
    }
    //3.生成文件方法（targetPathFileName生成目标文件名：[path+"className.*"]）
    public static void freemarkerGenerator(String targetPathFileName, Map<String,Object> map) throws IOException, TemplateException {
        //调整参数（生成文件名[路径+类名]）：targetPath+"Test.java = targetPathFileName
        FileWriter fileWriter=new FileWriter(targetPathFileName);
        BufferedWriter bufferedWriter=new BufferedWriter(fileWriter);
        //放入\GeneratorApplication定义的变量
        //List<FieldUtil> fieldUtilList= DataBaseUtil.getColumnByTableName(tableName);
        //根据类信息，获取所有的set类型集合
        //  Set<String> typeSet=getJavaTypes(fieldUtilList);
        //  Map<String,Object> map=new HashMap<>();
        template.process(map,bufferedWriter);
        bufferedWriter.flush();
        fileWriter.close();
    }
}
